<?php

namespace App\Repositories\Services;

use App\Lib\Tool\Pwd;
use App\Lib\Tool\Ustring;
use App\Repositories\Contracts\AdminRepository;
use App\Repositories\Eloquent\Admin\AdminModel;
use App\Repositories\Eloquent\Admin\AdminOnlineModel;
use App\Task\Admin\Address;
use EasySwoole\Component\Singleton;
use EasySwoole\EasySwoole\Task\TaskManager;
use EasySwoole\Session\Session;

class Admin implements AdminRepository
{
    use Singleton;
    public $admin;
    public $session;
    public $status;
    public $msg;
    public $adminModel;
    public $adminOnlineModel;

    // 错误信息
    public $errors = array(
        0 => '系统异常',
        1 => '登录成功',
        2 => '用户名或密码不正确',
        3 => '登录非法',
        4 => 'ip有变化',
        5 => '您尚未登录或登录已超时',
        6 => '用户名或密码错误',
        7 => '您的帐号已被禁用',
        8 => '登录超时',
        9 => '此帐号已登录，不能重复登录',
        110 => '用户名错误',
        111 => '密码错误',
        120 => '系统解码错误',
        130 => '图形验证码错误',
    );
    function __construct()
    {
       $this->adminModel = new AdminModel();
       $this->adminOnlineModel = new AdminOnlineModel();
    }

    public function checkLogin()
    {
        $this->status = 0;
        $this->session =Session::getInstance()->get(USER_SESSION_ADMIN);
        if(empty($this->session)){
            return $this->returnError(5);
        }
        $AdminOnlineObj = $this->adminOnlineModel->getItemByAdminId($this->session['id']);
        if(empty($AdminOnlineObj)){

            return $this->returnError(5);
        }
        //超时
        if(time()-$AdminOnlineObj->active_time > USER_SESSION_TIME_OUT){
            return $this->returnError(8);
        }
        //更新最后活动时间
        $this->adminOnlineModel->setOnlineActiveTime($this->session['id']);
        $this->status = $this->session['id'];

        $adminObj = $this->adminModel->get($this->session['id']);


        return $this->returnError(1,$adminObj->toArray());
    }




    public function login(string $account = '', string $password, string $code = '',string $_clientIp = '')
    {
        $this->status = 0;
        if (!$account) {
            return $this->returnError(110);
        }
        if (!$password) {
            return $this->returnError(111);
        }
        //判断验证码
        if(Session::getInstance()->get('code') != $code || $code == ''){
            return $this->returnError(130);
        }
        $adminObj = $this->adminModel->getItemByAccount($account);
        if(empty($adminObj)){
            return $this->returnError(110);
        }
        $acode = $adminObj->acode;
        if(Pwd::getPass($password,$acode) != $adminObj->password){
            return $this->returnError(111);
        }
        //用户状态
        if($adminObj->status < 1){
            return $this->returnError(7);
        }
        $this->loginSuccess($adminObj,$_clientIp);
        $this->status = 1;
        return $this->returnError(1);

    }

    //登录成功后的操作
    public function loginSuccess($adminObj,$_clientIp){

        //设置session 信息
        $uid = $adminObj->id;
        $login_key = $this->getLoginKey($uid,$_clientIp);
        $session = [];
        $session['id'] = $uid;
        $session['active_time'] = time();
        $session['login_key'] = $login_key;
        $session['ip'] = $_clientIp;
        Session::getInstance()->set(USER_SESSION_ADMIN,$session);


        $this->admin = $adminObj;
        $this->admin->login_key = $login_key;
        $this->admin->ip = $_clientIp;
        //单点登录操作
        $count = $this->adminOnlineModel->getCountByAdminId($uid);
        //注销登录
        if($count > 0){
            $this->adminOnlineModel->delByAdminId($uid);
        }
        $item['id_admin'] = $this->admin->id;
        $item['ip'] = $this->admin->ip;
        $item['login_key'] = $this->admin->login_key;
        $item['active_time'] = time();
        $item['add_date'] = date('Ymd');
        $this->adminOnlineModel->createAdminOnline($item);

        $task = TaskManager::getInstance();
        $task->async(new Address($item));

    }


    public function logout()
    {
        $this->session =Session::getInstance()->get(USER_SESSION_ADMIN);
        $this->adminOnlineModel->delByAdminId($this->session['id']);
    }


    public function __set($name, $value) {
        $this->$name=$value;
    }
    public function __get($name) {
        return $this->$name;
    }

    public function returnError(int $index = 0,$admin = []) {
      return [$this->status,$this->errors[$index],$admin];
    }

    protected function getLoginKey($uid,$ip) {
        return substr(md5(microtime(true) . $uid . $ip . Ustring::randString(8)), 0, 20);
    }

}